import axios from 'axios';
import { UniAdapter } from 'uniapp-axios-adapter';
import { getToken, removeToken } from './auth';
import baseURL from './baseURL';
import store from '@/store';

const COMMON_API = ['sysDict', 'sysDictType', 'sysDynamicText'];
let isLoading = false;
const request = axios.create({
	baseURL: baseURL + '/store',
	timeout: 5000,
	adapter: UniAdapter
});
let reqCount = 0;
request.interceptors.request.use(config => {
	// 如果当前没有显示加载动画，则显示它
	// if (!isLoading && reqCount == 0) {
	// 	uni.showLoading({ title: '加载中...' });
	// 	isLoading = true;
	// }
	// 请求计数
	const regex = /\/([^\/]+)\//;
	const match = regex.exec(config.url);
	// if (match && COMMON_API.includes(match[1])) {
	// 	config.baseURL = baseURL;
	// }
	reqCount++;
	//带上token
	config.headers['token'] = getToken();
	config.headers['deviceType'] = 'app';
	config.headers['type'] = 'store';
	return config;
});

request.interceptors.response.use(
	response => {
		if (isLoading) {
			// 隐藏加载动画
			// uni.hideLoading();
			isLoading = false;
		}
		// console.log(response);
		// 统一处理响应,返回Promise以便链式调用
		reqCount--;
    
		if (response.status === 200) {
			const { data } = response;
			if (data && data.code === 200) {
				return Promise.resolve(data);
			} else if (reqCount === 0 && data && data.code === 401) {
				removeToken();
				console.log('11111');
				// store.dispatch('car/addToCar', { total: 0, size: 0 });
        // uni.removeStorageSync('customerPhone');
        console.log('reqCount', reqCount);
				uni.utils.toast('请先登录');
				let timer = setTimeout(() => {
					clearTimeout(timer);
					timer = null;
					uni.navigateTo({ url: '/pages/login/login' });
				}, 500);
				return Promise.reject(data);
			} else {
				console.log('reqCount', reqCount);
				uni.utils.toast(data.message);
				return Promise.reject(data);
			}
		} else {
			uni.utils.toast('服务器异常，联系管理员');
      // reqCount--;
      console.log('reqCount', reqCount);
			const { data } = response;
			return Promise.reject(data);
    }
    
	},
	error => {
		reqCount--;
		// 请求失败时也隐藏加载动画
		// if (isLoading) {
		// 	// 隐藏加载动画
		// 	// uni.hideLoading();
		// 	isLoading = false;
    // }
    console.log('reqCount', reqCount);
		console.log('error', error);
		if (error.errMsg.includes('timeout') || error.errMsg === 'Network Error') {
			uni.utils.toast('网络超时');
			return Promise.reject(error);
		} else {
			uni.utils.toast('网络超时');
			return Promise.reject(error);
		}
	}
);

export default request;
